package com.android.manghe.orderpay.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.Glide.GlideHelper
import com.android.base.tools.ToastUtil
import com.android.manghe.R
import com.android.manghe.cache.ConfigHolder
import com.android.manghe.config.ConstantsUrl
import com.android.manghe.config.events.PaySuccessEvent
import com.android.manghe.config.events.RefreshCartEvent
import com.android.manghe.config.events.RefreshMemberInfoEvent
import com.android.manghe.member.activity.BuyMemberActivity
import com.android.manghe.mine.activity.AddressListActivity
import com.android.manghe.mine.model.AddressInfo
import com.android.manghe.orderpay.model.MarketOrderInfoRes
import com.android.manghe.orderpay.presenter.PNoPriceMarketOrder
import com.android.manghe.utils.AnalyzeUtil
import com.android.manghe.zhuli.activity.WebTextActivity
import com.android.manghe.zhuli.activity.ZhuLiProgressActivity
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import kotlinx.android.synthetic.main.activity_order_pay_no_price.*
import kotlinx.android.synthetic.main.layout_buy_member_dialog.*
import java.text.DecimalFormat

/**
 * 免单付款（单个商品）。确认订单界面，  底部有结算按钮，直接结算
 */
class NoPriceMarketOrderPayActivity : MVPActivity<PNoPriceMarketOrder>() {

    private val ReqCode_SelectAddress = 1000

    override fun getLayoutId(): Int {
        return R.layout.activity_order_pay_no_price
    }

    override fun initData(savedInstanceState: Bundle?) {
        Bus.observe<PaySuccessEvent>().subscribe {
            Bus.send(RefreshCartEvent())
            finish()
        }.registerInBus(this)
        Bus.observe<RefreshMemberInfoEvent>().subscribe {
            p.getMemberInfo()
        }.registerInBus(this)

        p.goodId = intent.getStringExtra("goodId")
        p.spec = intent.getStringExtra("spec")
        p.qty = intent.getIntExtra("qty", 1)
        p.perPrice = intent.getStringExtra("perPrice")
        titleBar.setToolbar("确认订单").setLeftIcon(R.mipmap.icon_back_black)
            .setTitleAndStatusBgColor(R.color.white)



        p.getMemberInfo()
        p.loadAddressList()
        tvTotalQtyTip.text = "共${p.qty}件商品"

        layoutAddress.setOnClickListener {
            //添加地址,切换地址
            open(
                AddressListActivity::class.java,
                hashMapOf<String, Any>("isToSelect" to true),
                ReqCode_SelectAddress
            )
        }
        tvPay.setOnClickListener {
            if (p.currentAddress == null) {
                ToastUtil.showShort(this@NoPriceMarketOrderPayActivity, "请填写配送地址")
            } else if (p.orderInfo != null) {
                if (p.memberBean != null) {
                    if (p.memberBean.level == 0) {
                        //不是会员
                        dialogBuyMember.visibility = View.VISIBLE
                        val config = ConfigHolder.getConfigInfo(this)
                        if (config != null && config.order_exempt_rule_switch == 1) {
                            titleBar.setRightText("规则") {
                                AnalyzeUtil.clickRule(this, 2)
                                WebTextActivity.showActivity(
                                    this,
                                    "商品助力规则",
                                    ConstantsUrl.domain + ConstantsUrl.ZHULI_RULE
                                )
                            }.setRightFontColor(ContextCompat.getColor(this, R.color.colorFont99))
                        }
                    } else {
                        if(p.memberBean.exemptAmount == 0.0){
                            ToastUtil.showShort(this@NoPriceMarketOrderPayActivity, "抵用金不足")
                            return@setOnClickListener
                        }
                        p.toPay(etMark.text.toString().trim())
                    }
                }
            }
        }
        layoutBuyMember.setOnClickListener {
            //购买会员
            titleBar.setRightText(""){}
            dialogBuyMember.visibility = View.GONE
            open(BuyMemberActivity::class.java)
        }
        ivCloseRound.setOnClickListener {
            dialogBuyMember.visibility = View.GONE
            titleBar.setRightText(""){}
        }
    }

    //生成订单完成，打开订单列表界面和面单进度界面
    fun buildOrderDone(orderSN: String, thumb: String, name: String){
        ZhuLiProgressActivity.showActivity(this, orderSN, 0f, thumb, name)
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (ReqCode_SelectAddress == requestCode) {
                p.setCurrentAddress(data?.getSerializableExtra("addressInfo") as AddressInfo)
                showAddress(p.currentAddress)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    fun showGoodDetail(detail: MarketOrderInfoRes.DataBean?) {
        try {
            if (detail != null) {
                var goodInfo: MarketOrderInfoRes.DataBean.CartGoodsBean? = null
                for (bean in detail.cart_goods) {
                    if (bean.goods_id == p.goodId) {
                        goodInfo = bean
                        break
                    }
                }
                if (goodInfo == null) {
                    ToastUtil.showLong(this, "获取订单信息失败")
                    finish()
                    return
                }
                GlideHelper.loadWithHolderErr(this, goodInfo.img_src, ivGoodPic)
                tvGoodTitle.text = goodInfo.goods_name
                tvSpecName.text = "${goodInfo.goods_spec}"
                tvQyt.text = "x${p.qty}"
                tvExemptAmount.text = "余额：￥${p.memberBean.exemptAmount}"
                tvPerPrice.text = "￥${p.perPrice}"
                setPriceView()
                return
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        ToastUtil.showShort(this, "获取订单信息出错")
    }

    private fun setPriceView(){
        p.detailInfo?.let {
            var price = it.total.goods_amount.toDouble()
            if (price < 0) {
                price = 0.0
            }
            val format = DecimalFormat("0.00")
            val priceStr = format.format(price)
            tvTruePrice.text = "￥$priceStr"
            tvPriceSmall.text = tvTruePrice.text
        }
    }

    fun showAddress(addressInfo: AddressInfo?) {
        p.setCurrentAddress(addressInfo)
        if (addressInfo == null) {
            layoutAddAddress.visibility = View.VISIBLE
            layoutHaveAddress.visibility = View.GONE
        } else {
            layoutAddAddress.visibility = View.GONE
            layoutHaveAddress.visibility = View.VISIBLE

            tvAddrName.text = addressInfo.name
            tvAddrTel.text = addressInfo.mobile
            tvAddr.text = addressInfo.area + " " + addressInfo.address
        }
    }

    fun getInfoFail() {
        ToastUtil.showLong(this, "获取信息失败，请重试！")
        finish()
    }
}